package com.yc.jpyy.base.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;

import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;

public class Serialize {

	/**
	 * 序列化
	 * @param list
	 * @return
	 */
	public static byte[] serializeKryo(String value) {
		Kryo kryo = new Kryo();
		kryo.register(String.class);
		OutputStream outputStream = new ByteArrayOutputStream(8192);
		Output out = new Output(outputStream);
		out.setPosition(0);
		kryo.writeObject(out, value);
		//Zip.encode(out.getBuffer(), out);
		return out.getBuffer();
	}

	public static String unserializeKryo(byte[] bytes) {
		ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
		//bytes = Zip.decode(bis);
		Kryo kryo = new Kryo();
		kryo.register(String.class);
		//bis = new ByteArrayInputStream(bytes);
		return kryo.readObject(new Input(bis), String.class);
	}

	public static Object unserialize(byte[] bytes) {
		ByteArrayInputStream bais = null;
		ObjectInputStream ois = null;
		try {
			//反序列化
			bais = new ByteArrayInputStream(bytes);
			ois = new ObjectInputStream(bais);
			return ois.readObject();
		} catch (Exception e) {

		} finally {
			try {
				ois.close();
				bais.close();
			} catch (Exception e) {
			}
		}
		return null;
	}

	public static byte[] serialize(Object object) {
		ObjectOutputStream oos = null;
		ByteArrayOutputStream baos = null;
		try {
			//序列化
			baos = new ByteArrayOutputStream();
			oos = new ObjectOutputStream(baos);
			oos.writeObject(object);
			byte[] bytes = baos.toByteArray();
			return bytes;
		} catch (Exception e) {

		} finally {
			try {
				oos.close();
				baos.close();
			} catch (Exception e) {
			}
		}
		return null;
	}
}
